package org.example.controller;

import jakarta.servlet.http.HttpServletResponse;
import org.example.service.LoanOverdueStatisticsExcelService;
import org.example.service.LoanOverdueStatisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 贷款逾期统计控制器
 */
@RestController
@RequestMapping("/api/loan-overdue-statistics")
public class LoanOverdueStatisticsController {

    @Autowired
    private LoanOverdueStatisticsExcelService loanOverdueStatisticsExcelService;
    @Autowired
    private LoanOverdueStatisticsService loanOverdueStatisticsService;

    /**
     * 导入Excel文件
     * @param file Excel文件
     * @return 导入结果
     */
    @PostMapping("/import")
    public ResponseEntity<Map<String, Object>> importData(@RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证文件
            if (file.isEmpty()) {
                result.put("success", false);
                result.put("message", "文件不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            // 验证文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null ||
                    (!originalFilename.endsWith(".xlsx") && !originalFilename.endsWith(".xls"))) {
                result.put("success", false);
                result.put("message", "文件格式不正确，请上传Excel文件(.xlsx或.xls)");
                return ResponseEntity.badRequest().body(result);
            }

            // 执行导入
            int count = loanOverdueStatisticsExcelService.importExcel(file);

            result.put("success", true);
            result.put("message", "导入成功");
            result.put("count", count);

            return ResponseEntity.ok(result);

        } catch (IOException e) {
            result.put("success", false);
            result.put("message", "文件读取失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "导入失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 导出所有Excel文件
     * @param response HTTP响应
     * @throws IOException IO异常
     */
    @GetMapping("/export")
    public void exportData(HttpServletResponse response) throws IOException {
        loanOverdueStatisticsExcelService.exportExcel(response);
    }

    /**
     * 根据贷款类型导出Excel文件
     * @param loanType 贷款类型
     * @param response HTTP响应
     * @throws IOException IO异常
     */
    @GetMapping("/export/loan-type/{loanType}")
    public void exportDataByLoanType(@PathVariable String loanType, HttpServletResponse response) throws IOException {
        loanOverdueStatisticsExcelService.exportExcelByLoanType(loanType, response);
    }

    /**
     * 根据维度导出Excel文件
     * @param dimension 维度
     * @param response HTTP响应
     * @throws IOException IO异常
     */
    @GetMapping("/export/dimension/{dimension}")
    public void exportDataByDimension(@PathVariable String dimension, HttpServletResponse response) throws IOException {
        loanOverdueStatisticsExcelService.exportExcelByDimension(dimension, response);
    }

    /**
     * 根据条件查询数据
     * @param loanType 贷款类型
     * @param dimension 维度
     * @return 数据列表
     */
    @GetMapping("/data")
    public ResponseEntity<Map<String, Object>> getData(
            @RequestParam(value = "loanType", required = false) String loanType,
            @RequestParam(value = "dimension", required = false) String dimension) {
        Map<String, Object> result = new HashMap<>();
        try {
            var dataList = loanOverdueStatisticsService.queryByCondition(loanType, dimension);
            result.put("success", true);
            result.put("data", dataList);
            result.put("count", dataList.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询数据失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取所有数据
     * @return 数据列表
     */
    @GetMapping("/data/all")
    public ResponseEntity<Map<String, Object>> getAllData() {
        Map<String, Object> result = new HashMap<>();
        try {
            var dataList = loanOverdueStatisticsService.getAllData();
            result.put("success", true);
            result.put("data", dataList);
            result.put("count", dataList.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询数据失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据贷款类型获取数据
     * @param loanType 贷款类型
     * @return 数据列表
     */
    @GetMapping("/data/loan-type/{loanType}")
    public ResponseEntity<Map<String, Object>> getDataByLoanType(@PathVariable String loanType) {
        Map<String, Object> result = new HashMap<>();
        try {
            var dataList = loanOverdueStatisticsService.getByLoanType(loanType);
            result.put("success", true);
            result.put("data", dataList);
            result.put("count", dataList.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询数据失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据维度获取数据
     * @param dimension 维度
     * @return 数据列表
     */
    @GetMapping("/data/dimension/{dimension}")
    public ResponseEntity<Map<String, Object>> getDataByDimension(@PathVariable String dimension) {
        Map<String, Object> result = new HashMap<>();
        try {
            var dataList = loanOverdueStatisticsService.getByDimension(dimension);
            result.put("success", true);
            result.put("data", dataList);
            result.put("count", dataList.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询数据失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据ID查询详情
     * @param id 主键ID
     * @return 数据详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getById(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            var data = loanOverdueStatisticsService.getById(id);
            if (data != null) {
                result.put("success", true);
                result.put("data", data);
            } else {
                result.put("success", false);
                result.put("message", "数据不存在");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询数据失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 新增数据
     * @param data 数据对象
     * @return 操作结果
     */
    @PostMapping
    public ResponseEntity<Map<String, Object>> save(@RequestBody org.example.entity.LoanOverdueStatistics data) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = loanOverdueStatisticsService.save(data);
            result.put("success", success);
            result.put("message", success ? "保存成功" : "保存失败");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "保存失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 更新数据
     * @param data 数据对象
     * @return 操作结果
     */
    @PutMapping
    public ResponseEntity<Map<String, Object>> update(@RequestBody org.example.entity.LoanOverdueStatistics data) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = loanOverdueStatisticsService.updateById(data);
            result.put("success", success);
            result.put("message", success ? "更新成功" : "更新失败");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据ID删除数据
     * @param id 主键ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> delete(@PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = loanOverdueStatisticsService.removeById(id);
            result.put("success", success);
            result.put("message", success ? "删除成功" : "删除失败");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}
